{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aa47f524",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7^5 mod 13 = 11\n"
     ]
    }
   ],
   "source": [
    "def mod_pow(base, exponent, modulus):\n",
    "    result = 1\n",
    "\n",
    "    # 将指数展开为二进制形式，从高位到低位逐位处理\n",
    "    while exponent > 0:\n",
    "        # 如果当前位是1，则乘上当前的 base，然后取模\n",
    "        if exponent % 2 == 1:\n",
    "            result = (result * base) % modulus\n",
    "        # 将 base 平方，然后取模\n",
    "        base = (base * base) % modulus\n",
    "        # 右移一位，相当于除以2\n",
    "        exponent //= 2\n",
    "\n",
    "    return result\n",
    "\n",
    "# 示例：计算 (7^5) % 13\n",
    "a = 7\n",
    "c = 5\n",
    "n = 13\n",
    "result = mod_pow(a, c, n)\n",
    "print(f\"{a}^{c} mod {n} = {result}\")\n",
    "# 7^5 mod 13 = 11"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "955b4640",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
